<?php

namespace app\qsapi\service;

use app\qsapi\model\BoxGameOpen;
use app\qsapi\model\BoxHotKeys;
use app\qsapi\model\game\BoxGamePindaoSort;
use DOMDocument;
use think\Db;

class HomeService extends BaseService
{

    /**
     * 首页数据
     * @param $param
     * @return array
     */
    public function home($param): array
    {
        return api_message([], '操作成功');
        //首页banner信息
        $info['banner'] = (new BoxAdService())->getBannerList();

        //首页频道排序
        $plateScene = $this->getPlate() ?? 'all';
        $plateScene = $this->plateScene[$plateScene] ?? 1;
        $info['channel_sort'] = (new BoxGamePindaoSort())->field('id,name,icon,select_icon')->where(['status' => 1, 'mark' => 1, 'scene' => $plateScene])->where(function ($query) {
            $query->where(Db::raw("FIND_IN_SET('1',device)"));
            if (isset($this->adDevice[$this->getPlatform()])) {
                $device = $this->adDevice[$this->getPlatform()];
                $query->whereOr(Db::raw("FIND_IN_SET('{$device}',device)"));
            }
        })->order('sort desc')->select()->toArray();
        array_walk($info['channel_sort'], function (&$v) {
            $v['select_name'] = ['id' => $v['id']];
        });

        //游戏开服
        $start_time = strtotime(date("Y-m-d") . " 00:00:00");
        $end_time = strtotime(date("Y-m-d") . " 23:59:59");
        $gameOpenModel = new BoxGameOpen();
        $hourList = $gameOpenModel->field(["FROM_UNIXTIME(open_time, '%H') AS name"])->where([['mark', '=', 1], ['status', '=', 1], ['open_time', 'between', [$start_time, $end_time]]])->group("FROM_UNIXTIME(open_time, '%H')")->order("open_time ASC")->select();
        $time_list = [];
        if (!empty($hourList)){
            foreach ($hourList as $key => $hourItem){
                $tempArr = array(
                    "name" => $hourItem['name'] . ":00",
                    "checked" => $key == 0 ? 1 : 0
                );
                $time_list[] = $tempArr;
            }
        }
        $info['time_list'] = array_values($time_list);

        //tab菜单
        $info['menu_list']=(new BoxAdService())->getResource($param);
        return api_message($info);
    }


    /**
     * v2版本获取开服时间
     * @return array
     */
     public  function openTime(){
         $start_time = strtotime(date("Y-m-d") . " 00:00:00");
         $end_time = strtotime(date("Y-m-d") . " 23:59:59");
         $gameOpenModel = new BoxGameOpen();
         $hourList = $gameOpenModel->field(["FROM_UNIXTIME(open_time, '%H') AS name"])->where([['mark', '=', 1], ['status', '=', 1], ['open_time', 'between', [$start_time, $end_time]]])->group("FROM_UNIXTIME(open_time, '%H')")->order("open_time ASC")->select();
         $time_list = [];
         if (!empty($hourList)){
             foreach ($hourList as $key => $hourItem){
                 $tempArr = array(
                     "name" => $hourItem['name'],
                     "checked" => $key == 0 ? 1 : 0
                 );
                 $time_list[] = $tempArr;
             }
         }
//         $num = 24;
//         $time_list = [];
//         for ($i = 1; $i < $num; $i++) {
//             $today = date('Y-m-d');
//             $time = date('H:00', strtotime("$today +{$i} hour"));
//             $time_list[$i]['name'] = $time;
//             $time_list[$i]['checked'] = (date('H') == date('H', strtotime($time))) ? 1 : 0;
//         }
         return api_message(array_values($time_list));
     }

    /**
     * 千年v1.2.0版本获取开服时间
     * type 不传：兼容老版本获取当天的开服时间点，1、获取全部日期的开服时间点，2、获取特定日期的开服时间点
     * @return array
     */
     public function getOpenTime($param){
         $type = $param['type'] ?? "";
         $map = [
             ['mark', '=', 1],
             ['status', '=', 1],
         ];
         if ($type == 1){
             //获取全部日期的开服时间点

         } else if ($type == 2){
             $day = $param['day'] ?? "";
             if (empty($day)){
                 return api_message('', '日期参数错误', 0);
             }
             $map[] = ['open_time', 'between', [strtotime($day. " 00:00:00"), strtotime($day. " 23:59:59")]];
         } else {
             $map[] = ['open_time', 'between', [strtotime(date("Y-m-d") . " 00:00:00"), strtotime(date("Y-m-d") . " 23:59:59")]];
         }
         $gameId = $param['gameId']?? "";
         if (!empty($gameId)){
             $map[] = ['game_id', 'in', $gameId];
         }

         $gameOpenModel = new BoxGameOpen();
         $hourList = $gameOpenModel->field(["FROM_UNIXTIME(open_time, '%H') AS name"])->where($map)->group("FROM_UNIXTIME(open_time, '%H')")->order("name ASC")->select();

         $time_list = [];
         if (!empty($hourList)){
             foreach ($hourList as $key => $hourItem){
                 $tempArr = array(
                     "name" => $hourItem['name'].":00",
                     "checked" => $key == 0 ? 1 : 0
                 );
                 $time_list[] = $tempArr;
             }
         }
//         $num = 24;
//         $time_list = [];
//         for ($i = 1; $i < $num; $i++) {
//             $today = date('Y-m-d');
//             $time = date('H:00', strtotime("$today +{$i} hour"));
//             $time_list[$i]['name'] = $time;
//             $time_list[$i]['checked'] = (date('H') == date('H', strtotime($time))) ? 1 : 0;
//         }
         return api_message(array_values($time_list));
     }

    /**
     * 热搜词获取
     * @return array
     */
    public function getHostKeys(): array
    {
        $type = request()->param('type', 1);
        if(!in_array($type,[1,2])){
            return api_message([],'参数错误');
        }
        $hotKeysModel = new BoxHotKeys();
        $where[] = ['mark', '=', 1];
        $where[] = ['scene', '=', $type];
        $where[] = ['status', '=', 1];
        $list =$hotKeysModel->field('id,name,desc')->where($where)->order('sort desc');
        // 判断平台
        $platform = strtolower($this->platform) ?? '';
        if (isset($this->adDevice[$platform])) {
            $list = $list->where(function ($query) use ($platform) {
                $query->where(Db::raw("FIND_IN_SET('1',device)"));
                if (isset($this->adDevice[$platform])) {
                    $device = $this->adDevice[$platform];
                    $query->whereOr(Db::raw("FIND_IN_SET('{$device}',device)"));
                }
            });
        }
        $list = $list->select()->toArray();
        return api_message($list);
    }

    public static function plistDownload()
    {
        header('Content-Type: text/xml');
        header('Content-Disposition: attachment; filename="example.plist"');
// 定义应用信息
        $appInfo = [
            'bundle_identifier' => 'com.clophone.zycloudbox',
            'bundle_version'    => '1.0',
            'app_title'         => '掌娱云手机',
            'ipa_url'           => 'http://download.clophone.com/FS7d55nICDKxlgd8.ipa', // 确保这是你的IPA文件的真实URL
        ];

// 创建一个新的DOMDocument对象
        $dom = new DOMDocument('1.0', 'UTF-8');
        $dom->formatOutput = true;

// 添加根元素 <plist>
        $plist = $dom->createElement('plist');
        $plist->setAttribute('version', '1.0');
        $dom->appendChild($plist);

// 添加 <dict> 元素
        $dict = $dom->createElement('dict');
        $plist->appendChild($dict);

// 添加 items 数组
        $items = $dom->createElement('key', 'items');
        $dict->appendChild($items);
        $itemsArray = $dom->createElement('array');
        $dict->appendChild($itemsArray);

// 添加单个 item 的字典
        $itemDict = $dom->createElement('dict');
        $itemsArray->appendChild($itemDict);

// assets 数组
        $assetsKey = $dom->createElement('key', 'assets');
        $itemDict->appendChild($assetsKey);
        $assetsArray = $dom->createElement('array');
        $itemDict->appendChild($assetsArray);

// asset 字典
        $assetDict = $dom->createElement('dict');
        $assetsArray->appendChild($assetDict);

// kind 和 url
        $kindKey = $dom->createElement('key', 'kind');
        $kindString = $dom->createElement('string', 'software-package');
        $assetDict->appendChild($kindKey);
        $assetDict->appendChild($kindString);

        $urlKey = $dom->createElement('key', 'url');
        $urlString = $dom->createElement('string', $appInfo['ipa_url']);
        $assetDict->appendChild($urlKey);
        $assetDict->appendChild($urlString);

// metadata 字典
        $metadataKey = $dom->createElement('key', 'metadata');
        $itemDict->appendChild($metadataKey);
        $metadataDict = $dom->createElement('dict');
        $itemDict->appendChild($metadataDict);

// metadata 中的键值对
        foreach (['bundle_identifier', 'bundle_version', 'title'] as $key) {
            $metaKey = $dom->createElement('key', $key);
            $metaValue = $dom->createElement('string', $appInfo[$key == 'title' ? 'app_title' : $key]);
            $metadataDict->appendChild($metaKey);
            $metadataDict->appendChild($metaValue);
        }

// 输出或者保存 plist 文件
        echo $dom->saveXML();

// 或者保存到文件
// $dom->save('path/to/output.plist');

    }

    public static function setHtmlPlist()
    {
//        $appInfo = [
//            'bundle_identifier' => 'com.clophone.zycloudbox',
//            'bundle_version'    => '1.0',
//            'app_title'         => '掌娱云手机',
//            'ipa_url'           => 'http://download.clophone.com/FS7d55nICDKxlgd8.ipa', // 确保这是你的IPA文件的真实URL
//        ];
        $plist_content = '<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>items</key>
    <array>
        <dict>
            <key>assets</key>
            <array>
                <dict>
                    <key>kind</key>
                    <string>software-package</string>
                    <key>url</key>
                    <string>http://download.clophone.com/FS7d55nICDKxlgd8.ipa</string>
                </dict>
            </array>
            <key>metadata</key>
            <dict>
                <key>bundle-identifier</key>
                <string>com.clophone.zycloudbox</string>
                <key>bundle-version</key>
                <string>1.0</string>
                <key>kind</key>
                <string>software</string>
                <key>title</key>
                <string>掌娱云手机</string>
            </dict>
        </dict>
    </array>
</dict>
</plist>';
        header('Content-Type: application/x-plist'); // 或者 text/xml
        header('Content-Disposition: attachment; filename="example.plist"');
        header('Content-Length: ' . strlen($plist_content));
        // 输出plist内容
        echo $plist_content;
    }
}